package main

import (
	"fmt"
	"net"
	"net/rpc"
	common "projRoot/commonLib"
)

func toNumber_recursive(raw string, pos int, maxpos int) int {
	if pos > maxpos {
		return 0
	}
	base := 1
	for i := pos + 1; i <= maxpos; i++ {
		base *= 10
	}
	var zero rune = rune('0')
	code := rune(raw[pos])
	return (int(code)-int(zero))*base + toNumber_recursive(raw, pos+1, maxpos)
}

func toNumber(raw string) int {
	return toNumber_recursive(raw, 0, len(raw)-1)
}

func main_func() {
	// 首先是通过rpc.Dial拨号RPC服务，然后通过client.Call调用具体的RPC方法
	TCP_conn, err := net.Dial("tcp", fmt.Sprintf(":%d", common.ServerPort))
	if err != nil {
		panic(err)
	}
	defer TCP_conn.Close()
	client := rpc.NewClient(TCP_conn)

	var client_portID, server_portID int
	{
		_, tmp, _ := net.SplitHostPort(TCP_conn.LocalAddr().String())
		client_portID = toNumber(tmp)
		_, tmp, _ = net.SplitHostPort(TCP_conn.RemoteAddr().String())
		server_portID = toNumber(tmp)
	}

	defer func() {
		result := common.LockState{}
		arguments := common.LockArguments{Client_portID: client_portID, Request_time: "12:50"}
		client.Call(fmt.Sprintf("%s.Release", common.LockServiceName), &arguments, &result)
	}()

	fmt.Printf("已TCP连接服务器, 本地端口号%d, 服务器端口号:%d\n",
		client_portID, server_portID)

	result := common.LockState{}

	arguments := common.LockArguments{Client_portID: client_portID, Request_time: "12:50"}
	err = client.Call(fmt.Sprintf("%s.Acquire", common.LockServiceName), &arguments, &result)
	arguments.Notebook = result.Notebook
	if err != nil {
		fmt.Printf("加锁失败: %v\n", err)
	} else {
		fmt.Println("RPC已返回加锁结果", result)
	}

	arguments.Request_time = "13:01"
	err = client.Call(fmt.Sprintf("%s.Release", common.LockServiceName), &arguments, &result)
	arguments.Notebook = result.Notebook
	if err != nil {
		fmt.Printf("解锁失败: %v\n", err)
	} else {
		fmt.Println("RPC已返回解锁结果", result)
	}

	arguments.Request_time = "12:50"
	err = client.Call(fmt.Sprintf("%s.Acquire", common.LockServiceName), &arguments, &result)
	arguments.Notebook = result.Notebook
	if err != nil {
		fmt.Printf("加锁失败: %v\n", err)
	} else {
		fmt.Println("RPC已返回加锁结果", result)
	}
}

func main() {
	main_func()
}
